package de.duester.genealogy;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import de.duester.genealogy.adapter.PersonListAdapter;
import de.duester.genealogy.model.Person;
import de.duester.genealogy.model.service.PersonService;

public class SelectPersonActivity extends Activity implements OnItemClickListener {
	private int position;
	private ListView lvSelectPerson;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_select_person);
		init();
	}

	private void init() {
		long personId = getIntent().getLongExtra("personId", -1);
		position = getIntent().getIntExtra("position", 0);
		int gender = getIntent().getIntExtra("gender", Person.ALL);

		lvSelectPerson = (ListView) findViewById(R.id.lvPersonList);
		lvSelectPerson.setAdapter(new PersonListAdapter(this, android.R.layout.simple_list_item_1,
				PersonService.getPersonsByGender(gender, Utility.getDaoSession().getPersonDao()
						.load(personId))));
		lvSelectPerson.setOnItemClickListener(this);
		registerForContextMenu(lvSelectPerson);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
		Intent intent = new Intent();
		intent.putExtra("position", this.position);
		intent.putExtra("personId", ((Person) lvSelectPerson.getItemAtPosition(position)).getId()
				.longValue());
		setResult(RESULT_OK, intent);
		finish();
	}
}
